package com.financial.service.yspay.service.impl;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.financial.service.yspay.connector.SysconfigFeign;
import com.financial.service.yspay.constants.YsServiceEnumConstants;
import com.financial.service.yspay.dto.FinancialYsPayDTO;
import com.financial.service.yspay.service.FinancialYsPayBuildRequestParaService;
import com.financial.service.yspay.service.FinancialYsPayVerifyJsonSignService;
import com.financial.service.yspay.service.FinancialYsSplitService;
import com.financial.service.yspay.utils.DateUtils;
import com.financial.service.yspay.utils.HttpUtils;
import com.financial.service.yspay.utils.JsonUtils;
import com.financial.service.yspay.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Davidbieber
 * @description 银盛分账验签实现类
 * @email davidbieber@163.com
 * @date 2019/11/18 4:03 PM
 */
@Service
public class FinancialYsSplitServiceImpl implements FinancialYsSplitService {
    private static final Logger logger= LoggerFactory.getLogger(FinancialYsSplitServiceImpl.class);

    @Value("${ysSplitNotifyUrl}")
    private String ysSplitNotifyUrl;

    @Value("${ysSplitMethod}")
    private String ysSplitMethod;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Autowired
    private FinancialYsPayBuildRequestParaService financialYsPayBuildRequestParaService;

    @Autowired
    private FinancialYsPayVerifyJsonSignService financialYsPayVerifyJsonSignService;

    @Override
    public ApiResult ysSplit(String requestParam) {
        logger.info("FinancialYsSplitServiceImpl.ysSplit()------银盛分账请求参数json为:"+requestParam);
        String ysPaySplitJson=sysconfigFeign.getServiceYsConfig();
        FinancialYsPayDTO financialYsSplitDTO= JsonUtils.parseObject(ysPaySplitJson);
        /*返回内容初始化*/
        String content = null;
        if (financialYsSplitDTO != null) {
            /*组装银盛微信支付参数信息*/
            Map<String,String> param = new HashMap<String,String>();
            param.put("method", ysSplitMethod);
            param.put("partner_id", financialYsSplitDTO.getPARTNER_ID());
            param.put("timestamp", DateUtils.getNowTimeStr());
            param.put("charset", financialYsSplitDTO.getDEFAULT_CHARSET());
            param.put("sign_type", financialYsSplitDTO.getSIGN_ALGORITHM());
            param.put("notify_url", ysSplitNotifyUrl);
            param.put("version", financialYsSplitDTO.getVERSION());
            /*获取biz_content业务参数信息*/
            param.put("biz_content", requestParam);
            logger.info("FinancialYsSplitServiceImpl.ysSplit()----->请求银盛分账参数为:" + param.toString());
            try {
                //签名
                Map<String,String> sPara = financialYsPayBuildRequestParaService.buildRequestPara(param, financialYsSplitDTO);
                //发起请求
                logger.info("FinancialYsSplitServiceImpl.ysSplit()----->签名完成的参数:"+JsonUtils.objectToJson(sPara));
                String returnString = HttpUtils.httpsSend(financialYsSplitDTO.getYSEPAY_GATEWAY_URL_DSF(), sPara);
                logger.info("FinancialYsSplitServiceImpl.ysSplit()----->银盛分账请求接口参数返回数据：" + JsonUtils.objectToJson(returnString));
                //回执参数JSON转map
                Map<String, Object> resultMap = (Map<String, Object>) JSON.parse(returnString);
                Map<String, String> obj = (Map<String, String>) resultMap.get("ysepay_single_division_online_accept_response");
                boolean verifyResult = false;
                if (obj == null) {
                    return ApiResult.failure(JsonUtils.objectToJson("银盛返回结果为空"));
                }
                int begin = returnString.indexOf("ysepay_single_division_online_accept_response");
                content = returnString.substring(begin);
                content = content.replace("ysepay_single_division_online_accept_response", "");
                content = content.substring(2, content.length() - 1);
                verifyResult = financialYsPayVerifyJsonSignService.verifyJsonSign(resultMap.get("sign").toString(), content, "utf-8",financialYsSplitDTO);
                logger.info("FinancialYsSplitServiceImpl.ysSplit()----->分账请求回执信息,验签是否成功content:"+content+"验签结果verifyResult--"+verifyResult);
                if (null == content || content.equals("")) {
                    logger.info("FinancialYsSplitServiceImpl.ysSplit()----->验签没有成功:银盛返回结果为空");
                    return ApiResult.failure(JsonUtils.objectToJson("银盛返回结果为空"));
                }
                /*解析contrent*/
                Map<String, Object> contentMap = JsonUtils.jsonToMap(content);
                boolean returnCodeState = contentMap.containsKey("returnCode");
                if(returnCodeState){
                    Object tempParams = contentMap.get("returnCode");
                    String returnCode = tempParams == null ? null : tempParams.toString();
                    if(returnCode.equalsIgnoreCase(YsServiceEnumConstants.ENUM_FPLITSTATE_SUC)){
                        /*0000是预分账成功标识*/
                        return ApiResult.success(content);
                    }else{
                        /*失败返回*/
                        return ApiResult.failure(content);
                    }
                }else{
                    /*失败返回*/
                    return ApiResult.failure(content);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e1) {
                e1.printStackTrace();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return ApiResult.failure(requestParam);
    }
}
